package com.voc.im.controller;

import com.alibaba.fastjson.JSON;
import com.jfoenix.controls.JFXBadge;
import com.voc.im.bean.*;
import com.voc.im.common.Constants;
import com.voc.im.controller.item.ItemChatController;
import com.voc.im.controller.item.ItemRoomController;
import com.voc.im.controller.item.ItemUserController;
import com.voc.im.bean.UserRoom;
import com.voc.im.model.*;
import io.datafx.controller.FXMLController;
import io.datafx.controller.flow.Flow;
import io.datafx.controller.flow.FlowException;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.geometry.Side;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.lang.ref.WeakReference;
import java.util.*;

@FXMLController("/fxml/sample.fxml")
public class MainController {

    @FXML
    private ListView<ChatEntry> listMainChat;
    @FXML
    private ListView<UserRoom> listMainUser, listMainGroup;
    @FXML
    private StackPane stack_main_chat;
    @FXML
    private Button btnMainChat, btnMainUser, btnMainGroup, btnAddObject;
    @FXML
    private ImageView imgMainChat, imgMainUser, imgMainGroup;

    @Inject
    private ChatRecordModel chatRecordModel;
    @Inject
    private UserRoomModel userRoomModel;

    private Map<Integer, StackPane> chatEntryStackPaneMap = new HashMap<>();
    private Map<Integer, StackPane> userRoomStackPaneMap = new HashMap<>();
    private Map<Integer, StackPane> windowsStackPaneMap = new HashMap<>();

    @PostConstruct
    public void init() {

        //初始聊天列表
        listMainChat.setCellFactory((ListView<ChatEntry> listView) -> new ChatEntryCell(this));
        listMainChat.getSelectionModel().selectedItemProperty().addListener(this::onChatItemListener);
        listMainChat.itemsProperty().bind(chatRecordModel.getEntryListProperty());
        chatRecordModel.getSelectedEntryIndex().bind(listMainChat.getSelectionModel().selectedIndexProperty());

        //初始好友列表
        listMainUser.setCellFactory((ListView<UserRoom> listView) -> new UserRoomCell(this));
        listMainUser.getSelectionModel().selectedIndexProperty().addListener(this::onUserItemListener);
        listMainUser.itemsProperty().bind(userRoomModel.getUserListProperty());
        userRoomModel.getSelectedUserIndex().bind(listMainUser.getSelectionModel().selectedIndexProperty());
        listMainUser.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {
            if (event.getButton() == MouseButton.SECONDARY) {
                System.out.println("右键单击..某事" + JSON.toJSONString(listMainUser.getSelectionModel().getSelectedItem()));
            }
        });

        //初始群聊列表
        listMainGroup.setCellFactory((ListView<UserRoom> listView) -> new UserRoomCell(this));
        //listMainGroup.getSelectionModel().selectedIndexProperty().addListener(new UserListener());
        listMainGroup.itemsProperty().bind(userRoomModel.getRoomListProperty());
        userRoomModel.getSelectedRoomIndex().bind(listMainGroup.getSelectionModel().selectedIndexProperty());

        UserRoom[] userRooms = new UserRoom[]{
                new UserRoom(1, "linlimin@openfire-voc", "linlimin", "林荔敏", Constants.USER_ROOM_1),
                new UserRoom(2, "lisi@openfire-voc", "lisi", "李四", Constants.USER_ROOM_1),
                new UserRoom(3, "zhangsan@openfire-voc", "zhangsan", "张三", Constants.USER_ROOM_1),
                new UserRoom(4, "wangwu@openfire-voc", "wangwu", "王五", Constants.USER_ROOM_1),
                new UserRoom(5, "dffffdf@openfire-voc", "dffffdf", "IM即使通讯沟通群", Constants.USER_ROOM_2),
                new UserRoom(6, "fddfdfd@openfire-voc", "fddfdfd", "福建沃晨信息科技", Constants.USER_ROOM_2)
        };

        ChatRecord[] chatRecords = new ChatRecord[]{
                new ChatRecord(1, 1, "linlimin this is test 1"),
                new ChatRecord(2, 1, "linlimin this is test 2"),
                new ChatRecord(3, 2, "lisi this is test 1"),
                new ChatRecord(4, 3, "zhangsan this is test 1"),
        };

        ChatLast[] chatLasts = new ChatLast[]{
                new ChatLast(1, 1, 2),
                new ChatLast(2, 2, 3),
                new ChatLast(3, 3, 4),
        };

        ChatEntry[] chatEntries = new ChatEntry[]{
                new ChatEntry(userRooms[0], chatRecords[1]),
                new ChatEntry(userRooms[1], chatRecords[2]),
                new ChatEntry(userRooms[2], chatRecords[3]),
        };

        //模拟添加聊天列表数据
        for (ChatEntry chatEntry : chatEntries) {
            List<ChatRecord> chatRecordList = new ArrayList<>();
            for (ChatRecord chatRecord : chatRecords) {
                if (chatEntry.getUserRoom().getId() == chatRecord.getUid()) {
                    chatRecordList.add(chatRecord);
                }
            }
            chatRecordModel.addPropertyMap(chatEntry, chatRecordList);
        }

        //模拟添加用户/群数据
        for (UserRoom userRoom : userRooms) {
            userRoomModel.addProperty(userRoom);
        }

        btnMainChat.setOnAction((e) -> {
            imgMainChat.setImage(new Image("/img/a1s.png"));
            imgMainUser.setImage(new Image("/img/a3.png"));
            imgMainGroup.setImage(new Image("/img/a2.png"));
            listMainChat.setVisible(true);
            listMainUser.setVisible(false);
            listMainGroup.setVisible(false);
            ObservableValue<ChatEntry> value = listMainChat.getSelectionModel().selectedItemProperty();
            this.onChatItemListener(value, value.getValue(), value.getValue());
        });

        btnMainUser.setOnAction((e) -> {
            imgMainChat.setImage(new Image("/img/a1.png"));
            imgMainUser.setImage(new Image("/img/a3s.png"));
            imgMainGroup.setImage(new Image("/img/a2.png"));
            listMainChat.setVisible(false);
            listMainUser.setVisible(true);
            listMainGroup.setVisible(false);
            ObservableValue<Number> value = listMainUser.getSelectionModel().selectedIndexProperty();
            this.onUserItemListener(value, value.getValue(), value.getValue());
        });

        btnMainGroup.setOnAction((e) -> {
            imgMainChat.setImage(new Image("/img/a1.png"));
            imgMainUser.setImage(new Image("/img/a3.png"));
            imgMainGroup.setImage(new Image("/img/a2s.png"));
            listMainChat.setVisible(false);
            listMainUser.setVisible(false);
            listMainGroup.setVisible(true);
        });

        btnAddObject.setOnAction(event -> {
            ContextMenu contextMenu = new ContextMenu();
            contextMenu.setStyle("-fx-background-color: #ffffff;-fx-padding: 5px; -fx-background-radius: 2px;");
            MenuItem addUser = new MenuItem("添加好友");
            MenuItem addRoom = new MenuItem("创建群聊");
            contextMenu.getItems().addAll(addUser, addRoom);
            contextMenu.show(btnAddObject, Side.BOTTOM, -45, 5);
        });

    }

    /**
     * 聊天列表item点击调用
     */
    private void onChatItemListener(ObservableValue<? extends ChatEntry> observable, ChatEntry oldValue, ChatEntry newValue) {
        if (newValue == null) {
            return;
        }
        chatRecordModel.getObjectProperty().setValue(newValue.getUserRoom());
        try {
            StackPane stackPane = windowsStackPaneMap.get(newValue.getUserRoom().getId());
            if (stackPane == null) {
                stackPane = new Flow(WindowChatController.class).start();
                windowsStackPaneMap.put(newValue.getUserRoom().getId(), stackPane);
            }
            stack_main_chat.getChildren().setAll(stackPane);
        } catch (FlowException e) {
            e.printStackTrace();
        }
    }

    /**
     * 好友列表item点击调用
     */
    private void onUserItemListener(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
        if (newValue.intValue() == -1) {
            return;
        }
        userRoomModel.getSelectedUserIndex().bind(observable);
        try {
            StackPane stackPane = new Flow(WindowUserController.class).start();
            stack_main_chat.getChildren().setAll(stackPane);
        } catch (FlowException e) {
            e.printStackTrace();
        }
    }


    /**
     * 消息列表item更新
     */
    static class ChatEntryCell extends ListCell<ChatEntry> {

        private WeakReference<MainController> weakReference;

        private ChatEntryCell(MainController controller) {
            this.weakReference = new WeakReference<>(controller);
        }

        @Override
        protected void updateItem(ChatEntry item, boolean empty) {
            super.updateItem(item, empty);
            MainController controller = weakReference.get();
            if (controller == null) {
                return;
            }
            if (item != null) {
                controller.chatRecordModel.getSelectedEntryIndex().bind(indexProperty());
                StackPane stackPane = controller.chatEntryStackPaneMap.get(item.getUserRoom().getId());
                try {
                    if (stackPane == null)
                        stackPane = new Flow(ItemChatController.class).start();
                    controller.chatEntryStackPaneMap.put(item.getUserRoom().getId(), stackPane);
                } catch (FlowException e) {
                    e.printStackTrace();
                }
                setGraphic(stackPane);
            } else {
                setGraphic(null);
            }
        }

    }


    /**
     * 好友/群聊列表item更新
     */
    static class UserRoomCell extends ListCell<UserRoom> {

        private WeakReference<MainController> weakReference;

        private UserRoomCell(MainController controller) {
            this.weakReference = new WeakReference<>(controller);
        }

        @Override
        protected void updateItem(UserRoom item, boolean empty) {
            super.updateItem(item, empty);
            MainController controller = weakReference.get();
            if (controller == null) {
                return;
            }
            if (item != null) {
                if (item.getType() == Constants.USER_ROOM_1) {
                    controller.userRoomModel.getSelectedUserIndex().bind(indexProperty());
                } else if (item.getType() == Constants.USER_ROOM_2) {
                    controller.userRoomModel.getSelectedRoomIndex().bind(indexProperty());
                }
                StackPane stackPane = controller.userRoomStackPaneMap.get(item.getId());
                try {
                    if (stackPane == null) {
                        if (item.getType() == Constants.USER_ROOM_1) {
                            stackPane = new Flow(ItemUserController.class).start();
                        } else if (item.getType() == Constants.USER_ROOM_2) {
                            stackPane = new Flow(ItemRoomController.class).start();
                        }
                    }
                    controller.userRoomStackPaneMap.put(item.getId(), stackPane);
                } catch (FlowException e) {
                    e.printStackTrace();
                }
                setGraphic(stackPane);
            } else {
                setGraphic(null);
            }
        }

    }


}
